const path = require('path');
const qs = require('query-string')
const fs = require('fs')
const UUID = require('uuid')

/***
 * qs.parse('a=1&b=2', keyDot, valueDot)  {a:'1',b:'2'}
 *  keyDot  key与key的分割符号  默认 &
 *  valueDot  key与value的分割符号  默认 =
 */
Buffer.prototype.split = function (boundary) {  // 实现buffer的split方法
    let arr = []
    let index = this.indexOf(boundary);
    let len = Buffer.from(boundary).length;
    let offset = 0;
    while (-1 !== (index = this.indexOf(boundary, offset))) {
        arr.push(this.slice(offset, index))
        offset = index + len
    }
    arr.push(this.slice(offset))
    // console.log(arr)
    return arr
}

// Buffer.from('aaaa|bbbb|cccc').split('|')

const bodyParse = function (dir) {
    return async (ctx, next) => {  // 利用中间件实现request.body
        ctx.request.body = await new Promise((resolve) => {
            const arr = []
            ctx.req.on('data', function (data) {
                arr.push(data)
            })
            ctx.req.on('end', function () {
                let type = ctx.get('Content-Type') // 取当报文的数据格式   json   form  文件格式
                let body;
                if (type === 'application/x-www-form-urlencoded') { // 表单格式
                    body = Buffer.concat(arr).toString()
                } else if (type.startsWith('text/plain')) { //文本格式
                    body = Buffer.concat(arr).toString()
                } else if (type.startsWith('application/json')) {  // json 格式
                    body = JSON.parse(Buffer.concat(arr).toString())
                } else if (type.startsWith('multipart/form-data')) {  // 文件格式
                    // console.log(type,)
                    let boundary = '--' + type.split('=')[1]
                    let lines = Buffer.concat(arr).toString().split(boundary).slice(1, -1) // Buffer split 封装一下
                    let formData = {}
                    lines.forEach(line => {
                        let [head, body] = line.split('\r\n\r\n'); // http规范中定义 key和value之间的分隔符
                        head = head.toString()
                        let key = head.match(/name="(.+?)"/)[1]
                        if (head.includes('filename')) {// 上传的文件放在 存在服务器upload目录
                            let content = line.slice(head.length + 4, -2)
                            dir = dir || path.join(__dirname, 'upload')
                            let filepath = UUID.v4()
                            console.log(dir, filepath)
                            let uploadUrl = path.join(dir, filepath)
                            formData[key] = {
                                filename: uploadUrl,
                                size: content.length
                            }
                            fs.writeFileSync(uploadUrl, content)
                        } else {
                            let value = body.toString()
                            formData[key] = value.slice(0, -2)
                        }
                    })
                    body = formData

                }
                resolve(body)
            })
        })
        await next()
    }
}

module.exports = bodyParse